package kubayaxi.video.client.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import kubayaxi.video.client.service.IDownloadRecordService;
import kubayaxi.video.mybatis.auto.dao.DownloadRecordMapper;
import kubayaxi.video.mybatis.auto.dao.VideoMapper;
import kubayaxi.video.mybatis.auto.model.DownloadRecord;
import kubayaxi.video.mybatis.auto.model.Video;
import kubayaxi.video.mybatis.customize.model.downloadRecord.dto.AddRecordDTO;
import kubayaxi.video.service.base.common.enums.DeleteEnum;
import kubayaxi.video.service.base.common.request.BaseRequest;
import kubayaxi.video.service.base.common.treadlocal.UserContent;
import kubayaxi.video.service.base.util.common.Asserts;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class DownloadRecordServiceImpl implements IDownloadRecordService {

    @Resource
    private DownloadRecordMapper downloadRecordMapper;
    @Resource
    private VideoMapper videoMapper;

    /**
     * 添加下载视频记录
     */
    @Override
    public void addRecord(BaseRequest<AddRecordDTO> dto) {
        AddRecordDTO data = dto.getData();
        Asserts.isNotNull(data.getVId(),"视频id为空");
        Video video = videoMapper.selectById(data.getVId());
        Asserts.isNotNull(video,"视频不存在");
        Long uId = UserContent.get();
        DownloadRecord downloadRecord = downloadRecordMapper.selectOne(new LambdaQueryWrapper<DownloadRecord>()
                .eq(DownloadRecord::getVId,data.getVId())
                .eq(DownloadRecord::getUId,uId)
                .eq(DownloadRecord::getDeleteStatus, DeleteEnum.NOT_DELETED.getCode()));
        // 下载过有记录了就把编辑时间改为当前时间,否则再新增记录
        if(ObjectUtil.isNotNull(downloadRecord)){
            downloadRecord.setEditTime(LocalDateTime.now());
            int update = downloadRecordMapper.updateById(downloadRecord);
            Asserts.isTrue(update == 1, "编辑视频下载记录失败");
        } else {
            DownloadRecord record = new DownloadRecord();
            record.setUId(uId);
            record.setVId(data.getVId());
            int insert = downloadRecordMapper.insert(record);
            Asserts.isTrue(insert == 1,"新增视频下载记录失败");
        }
    }
}
